module.exports = {
    state:{},
    config:{},
    localStorage:(function(){try{return sessionStorage;}catch(e){return null}})(),
    setLocalStorage:function(storage){
        if(storage && storage.setItem && storage.getItem && storage.removeItem){
            this.localStorage = storage;
        }
    },
    init:function(key,next){
        var config = {type:0};
        if(typeof next == 'function') {
            config.type = 1;
        }else if(typeof next == 'object' && next.type){
            config = next;
        }else if(typeof next == 'number'){
            config = {type:next};
        }
        if(!this.config[key]) this.config[key] = config;
    },
    set:function(key,value,next){
        this.init(key,next);
        if(this.config[key].type == 1 && this.localStorage) {
            this.localStorage.setItem(key,typeof value === 'string' ? value : JSON.stringify(value),next);
            //if(this.config[key].expires) this.localStorage.setItem(key + '_expires',new Date().getTime() + '_' + this.config[key].expires);
            return false;
        }
        this.state[key] = value;
    },
    get:function(key,next){
        this.init(key,next);
        if(this.config[key].type == 1 && this.localStorage){
            return this.localStorage.getItem(key,next)
        }else{
            return this.state[key];
        }
    },
    remove:function(key,next){
        this.init(key,next);
        if(this.config[key].type == 1 && this.localStorage){
            this.localStorage.removeItem(key,next);
        }else{
            this.state[key] = undefined;
            delete this.state[key];
            this.config[key] = undefined;
            delete this.config[key];
        }
    },
    clear:function(type,next){
        if(type == 1 && this.localStorage && this.localStorage.clear){
            this.localStorage.clear(next);
        }else if(type == undefined){
            this.state = {};
            this.config = {};
        }else{
            for(var key in this.config){
                if(this.config[key].type == type){
                    this.state[key] = undefined;
                    delete this.state[key];
                }
            }
        }
        // for(var key in this.config){
        //     if(this.config[key].type == type){
        //         this.config[key] = undefined;
        //         delete this.config[key];
        //     }
        // }
    }
}